package com.pospi.xstore.ui.count;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.xstore.R;
import com.pospi.xstore.adapter.CountSAdapter;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dialog.WaitingDialog;
import com.pospi.xstore.dto.CashierMsgDto;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.PareseJson;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuListView;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by acer on 2018/6/19.
 */

public class CountsActivity extends BaseActivity implements OnDateSetListener {
    @Bind(R.id.bt_count_start)
    TextView bt_count_start;

    @Bind(R.id.time_select)
    TextView time_select;
    @Bind(R.id.count_name)
    TextView count_name;
    @Bind(R.id.count_shop_name)
    TextView count_shop_name;
    @Bind(R.id.count_refresh)
    TextView count_refresh;
    @Bind(R.id.count_goods_num)
    TextView goodsNum;
    @Bind(R.id.count_hg)
    EditText count_hg;
    private GoodsDao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.counts_msg);
        dao = new GoodsDao(this);
        setTitle("盘点");
        ButterKnife.bind(this);
        time_select.setText(GetData.getYYMMDDTime());
        init();



    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    closeDialog();
                    Intent intent = new Intent(CountsActivity.this, CountListActivity.class);
                    intent.putExtra("date", time_select.getText().toString().trim());//日期
                    intent.putExtra("hg", count_hg.getText().toString().trim());//货柜
                    startActivity(intent);
                    break;
                case 2:
                    closeDialog();
                    break;

            }

        }
    };

    private void init() {
        int which = getSharedPreferences("islogin", Context.MODE_PRIVATE).getInt("which", 0);
        List<CashierMsgDto> cashierMsgDtos = new PareseJson().parese(getSharedPreferences("cashierMsgDtos", Context.MODE_PRIVATE).getString("cashierMsgDtos", ""));
        String name = cashierMsgDtos.get(which).getName();
        count_name.setText(name);
        count_shop_name.setText(getSharedPreferences("StoreMessage", MODE_PRIVATE).getString("Name", ""));
        bt_count_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getNet();
            }
        });
        time_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TimePickerDialog dialogYearMonthDay = new TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH_DAY)
                        .setTitleStringId("选择日期")
                        .setWheelItemTextSize(16)
                        .setCallBack(CountsActivity.this)
                        .build();
                dialogYearMonthDay.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");

            }
        });
        count_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //刷新商品数据
                new AlertDialog.Builder(CountsActivity.this)
                        .setMessage("刷新成功")
                        .setPositiveButton("是", null)
                        .show();
            }
        });
        goodsNum.setText(String.valueOf(dao.findGoodsNum()));
    }
    public static String COUNTS_ID = "counts_id";

    private void getNet() {
        showDialog("请求中...");
        RequestParams params = new RequestParams();
        params.put("sh_id", getSharedPreferences("StoreMessage", MODE_PRIVATE).getString("Id", ""));
        LoadServer.getConnect(this, Api.SYNC_COUNTS, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    Log.i("counst", new String(bytes));
                    JSONObject object = new JSONObject(new String(bytes));
                    if (object.getString("code").equals("1")) {
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);

                        JSONObject object1 = object.getJSONObject("data");
                        String countId = object1.getString("id");
                        SPHelper.getInstance().putString(COUNTS_ID, countId);
                    } else {
                        Message message = Message.obtain();
                        message.what = 2;
                        handler.sendMessage(message);
                        Toast.makeText(CountsActivity.this, object.getString("msg"), Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = Message.obtain();
                    message.what = 2;
                    handler.sendMessage(message);
                    Toast.makeText(CountsActivity.this, "返回格式错误", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Message message = Message.obtain();
                message.what = 2;
                handler.sendMessage(message);
                Toast.makeText(CountsActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        Date date = new Date(millseconds);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String time = format.format(date);
        time_select.setText(time);
    }
    private Dialog waitingDialog;
    public void showDialog(String msg) {
        if (waitingDialog == null) {
            waitingDialog = WaitingDialog.createLoadingDialog(this, msg);
            waitingDialog.show();
        }
    }

    public void closeDialog() {
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
    }
}
